using System;
using System.Net.Sockets;
using AppSpaces.Transport.Sockets.Auth.Common;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
using System.Net;

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	//TODO implement a blacklist with global connections to other ports
	class CheckIpBlacklist : ICheckIpBlacklist
	{
        private readonly ListOfExpiringIPAddressEntries localBlacklist;

		public CheckIpBlacklist(int entryLifetimeSeconds, int timerInterval)
		{
            localBlacklist = new ListOfExpiringIPAddressEntries(entryLifetimeSeconds, timerInterval);
		}

		public CheckIpBlacklist() : this(3600, 60000)
		{
		}

		public void In_InvalidAddress(EndPoint address)
		{
			//Console.WriteLine("CheckIpBlacklist.In_InvalidAddress");
			var addr = address as IPEndPoint;
			if (addr == null)
				return;
			localBlacklist.GetOrAdd(addr.Address);
		}

		public void In_Connection(TcpClient tcpClient)
		{
			//Console.WriteLine("CheckIpBlacklist.In_Connection");
			if (localBlacklist.Contains((tcpClient.Client.RemoteEndPoint as IPEndPoint).Address))
				Out_BlockedConnection(tcpClient);
			else
				Out_AllowedConnection(tcpClient);
		}

		public event TcpClientHandler Out_AllowedConnection;

        public event TcpClientHandler Out_BlockedConnection;

		public void Dispose()
		{
			if (localBlacklist != null)
				localBlacklist.Dispose();
		}
	}
}